package org.redis.cluster.command;

import java.util.Arrays;

import org.redis.cluster.Ordered;
import org.redis.cluster.config.ClientConfig;
import org.redis.cluster.interceptor.Interceptor;
import org.redis.cluster.interceptor.Invocation;
import org.redis.cluster.redis.RedisCommand;
import org.redis.cluster.redis.transport.RedisReply;
import org.redis.cluster.redis.transport.reply.RedisStatusReply;

public class ExplainCommandProcessor implements Interceptor,Ordered {
	
	private final static String COMMAND="EXPLAIN";
	
	private String command=COMMAND;

	@Override
	public RedisReply intercept(Invocation invocation) throws Throwable {
		RedisCommand command=invocation.getCommand();
		if(!isSupport(command)) {
			return invocation.invoke();
		}
		
		int newParameterCount=command.getParameterCount()-1;
		byte newParameters[][]=Arrays.copyOfRange(command.getParameters(), 1, command.getParameters().length);
		
		command.setParameterCount(newParameterCount);
		command.setParameters(newParameters);
		command.setCommand(null);
		command.setSource(null);
		
		RedisReply reply=invocation.invoke();
		ClientConfig target=command.getTarget();
		if(target==null) {
			return reply;
		}
		
		return new RedisStatusReply(target);
	}
	
	@Override
	public int getOrder() {
		return Ordered.MEDIUM;
	}

	protected boolean isSupport(RedisCommand command) {
		return command.getCommand().equals(getCommand()) && command.getParameterCount()>1;
	}
	
	public void setCommand(String command) {
		this.command = command;
	}
	public String getCommand() {
		return command;
	}
}